<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\exception\DbException;
use think\response\Json;

class Statistics extends Backend
{
    /**
     * Member模型对象
     * @var \app\admin\model\Member
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\statistics_model\Order();
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];


        return json($result);
    }


    /**
     * @author TechKoga
     * @date 2022/2/16
     * @describe 导出
     */
    public function export()
    {
        if ($this->request->isAjax()) {
            set_time_limit(0);
            ini_set('max_execution_time', 0);
            ini_set('memory_limit', -1);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $header = ['日期', '开始时段', '结束时段', '订单总数', '订单总金额'];
            $filePath = "uploads/csv/统计" . date('Y-m-d') . '_' . mt_rand(0, 99);

            //订单总数
            $count = $this->model
                ->field('date,start,end,num,money')
                ->where($where)
                ->count();

            if (empty($count)) {
                $this->error('当前搜索条件,没有数据能导出');
            }

            //单表数据量
            $sqlLimit = 100000;

            //到数量刷新buffer
            $limit = 5000;

            //计数器
            $cnt = 0;


            $fileNameArr = array();
            // 逐行取出数据，不浪费内存
            $page = ceil($count / $sqlLimit);
            for ($i = 0; $i < $page; $i++) {
                $fp = fopen($filePath . '_' . $i . '.csv', 'w'); //生成临时文件
                $fileNameArr[] = $filePath . '_' . $i . '.csv';

                //将数据通过fputcsv写到文件句柄
                fputcsv($fp, $header);

                $dataArr = $this->model
                    ->field('date,start,end,num,money')
                    ->where($where)
                    ->limit($i * $sqlLimit, $sqlLimit)
                    ->order('date asc,start asc')
                    ->select();

                foreach ($dataArr as $k => $v) {
                    $cnt++;
                    if ($limit == $cnt) {
                        //刷新一下输出buffer，防止由于数据过多造成问题
                        ob_flush();

                        $cnt = 0;
                    }
                    fputcsv($fp, $v->toArray());
                }
                fclose($fp);  //每生成一个文件关闭
            }

            //进行多个文件压缩
            $zip = new \ZipArchive();
            $filename = $filePath . '.zip';
            $zip->open($filename, \ZipArchive::CREATE);   //打开压缩包
            foreach ($fileNameArr as $file) {
                $zip->addFile($file, basename($file));   //向压缩包中添加文件
            }
            $zip->close();  //关闭压缩包
            foreach ($fileNameArr as $file) {
                unlink($file); //删除csv临时文件
            }

            //获取当前域名
            $domain = request()->domain();
            //输出下载地址
            $this->success('导出成功', $domain . "/" . $filename);
        }
    }

}